package com.rgs.se.concurrent.lock;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Ren Gaoshuai
 * @ClassName LocksObject
 * @Description 对象锁生成唯一id
 * @date 2021-10-27 11:00
 **/
public class LocksObject {

    private static int num = 0;

    //2个线程的线程池
    static ExecutorService executorService = Executors.newFixedThreadPool(2);

    /**
     * 主函数 模拟两个线程去获取分布式id
     * @param args
     */
    public static void main(String[] args) {
        OrderLock lock = new OrderLock();

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+","+lock.setInCrease());
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+","+lock.setInCrease());
                }
            }
        });

        /**
         * 以上就是模拟两个线程去获取id
         */

        executorService.shutdown();
        try {
            executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("num="+num);

    }

    /**
     * 静态内部类，用来获取唯一id
     */
    static class OrderLock{
        /**
         * 得到唯一的id
         * 时间+编号
         * @return
         */
        public synchronized String setInCrease(){
            num++;
            return getStringDateFormat() + num;
        }


    }

    /**
     * 获取当前时间字符串
     * 高并发情况下不能保证唯一，后面需要拼接编号
     * @return
     */
    public static String getStringDateFormat(){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
       return dtf.format(now);
    }
}
